﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;

namespace StampController
{
    /// <summary>
    ///     Summary description for handler
    /// </summary>
    public class Handler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var r = new List<DataUpload>();
            foreach (string file in context.Request.Files)
            {
                HttpPostedFile hpf = context.Request.Files[file];
                if (hpf != null)
                {
                    if (hpf.ContentLength == 0)
                        continue;
                    string originName;
                    if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" ||
                        HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                    {
                        string[] files = hpf.FileName.Split(new[] {'\\'});
                        originName = files[files.Length - 1];
                    }
                    else
                    {
                        originName = hpf.FileName;
                    }

                    string pathName = '/' + DateTime.Today.ToString("yyyyMMdd");
                    string uploadFolder = context.Server.MapPath(ConfigurationManager.AppSettings["UploadFolder"]);
                    if (!Directory.Exists(uploadFolder + pathName))
                    {
                        Directory.CreateDirectory(uploadFolder + pathName);
                    }

                    string fileName = pathName + "/file_" + DateTime.Now.ToString("hhmmss") +
                                      Path.GetExtension(originName);
                    string savedFileName = uploadFolder + fileName;
                    hpf.SaveAs(savedFileName);

                    //var reader = new BinaryReader(hpf.InputStream);
                    //var bytes = reader.ReadBytes(4);
                    //var text = Encoding.ASCII.GetString(bytes);

                    //if(text == "%PDF")
                    int pages = 1;
                    switch (hpf.ContentType)
                    {
                        case "application/pdf":
                            var sr = new StreamReader(hpf.InputStream);
                            string pdfText = sr.ReadToEnd();
                            var reg1 = new Regex(@"/Type\s*/Page[^s]");
                            MatchCollection matches = reg1.Matches(pdfText);
                            pages = matches.Count;
                            break;
                    }

                    r.Add(new DataUpload
                    {
                        ThumbnailUrl = savedFileName,
                        Name = ConfigurationManager.AppSettings["UploadFolder"] + fileName,
                        OriginName = originName,
                        Length = hpf.ContentLength,
                        Type = hpf.ContentType,
                        Pages = pages
                    });
                    var uploadedFiles = new
                    {
                        files = r.ToArray()
                    };
                    string jsonObj = new JavaScriptSerializer().Serialize(uploadedFiles);
                    context.Response.ContentType = "text/plain";
                    context.Response.ContentEncoding = Encoding.UTF8;
                    context.Response.Write(jsonObj);
                }
            }
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }

    public class DataUpload
    {
        public string ThumbnailUrl { get; set; }
        public string Name { get; set; }
        public string OriginName { get; set; }
        public int Length { get; set; }
        public int Pages { get; set; }
        public string Type { get; set; }
    }
}